#import "BCPreferencesController.h"

static BCPreferencesController* BCPreferencesControllerInstance = nil;

@implementation BCPreferencesController

+ (void) initialize
{
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary* defaultValues;
    
    defaultValues = [NSDictionary dictionaryWithObjectsAndKeys:
        [NSNumber numberWithBool: NO], @"AutoExpand",
        [NSNumber numberWithBool: NO], @"AutoClose",
        [NSNumber numberWithBool: NO], @"ReplaceFolderWithoutAsking", nil];
    
    [defaults registerDefaults: defaultValues];
}

+ (BCPreferencesController*) sharedPreferencesController
{
    if (BCPreferencesControllerInstance == nil)
        BCPreferencesControllerInstance = [[BCPreferencesController alloc] initWithWindowNibName: @"PreferencesWindow"];
    
    return BCPreferencesControllerInstance;
}

- (id) init
{
    NSAssert(FALSE, @"BCPreferencesController should not be instantiated. Use -sharedPreferencesController");
    
    return nil;
}

- (void) awakeFromNib
{
    [self loadDefaults];
}

- (void) loadDefaults
{
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    [_autoExpand setIntValue: [defaults boolForKey: @"AutoExpand"]];
    [_autoClose setIntValue: [defaults boolForKey: @"AutoClose"]];
    [_replaceFolderWithoutAsking setIntValue: [defaults boolForKey: @"ReplaceFolderWithoutAsking"]];
}

- (void) saveDefaults
{
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    [defaults setBool: ([_autoExpand intValue] > 0) forKey: @"AutoExpand"];
    [defaults setBool: ([_autoClose intValue] > 0) forKey: @"AutoClose"];
    [defaults setBool: ([_replaceFolderWithoutAsking intValue] > 0) forKey: @"ReplaceFolderWithoutAsking"];
}

- (IBAction) applyPreferences: (id)sender
{
    [self saveDefaults];
}

- (BOOL) autoExpand
{
    return ([_autoExpand intValue] > 0);
}

- (BOOL) autoClose
{
    return ([_autoClose intValue] > 0);
}

- (BOOL) replaceFolderWithoutAsking
{
    return ([_replaceFolderWithoutAsking intValue] > 0);
}

@end